<script lang="ts">
export default {
  name: "RepoCompEntityTable"
}
</script>

<template>
  <!-- 数据表单 -->
  <el-table
      ref="dataTableRef"
      v-loading="false"
      :data="dataState.entityList"
      border
      highlight-current-row
      @row-click="handleRowClick"
  >
    <!-- 展开列表 -->
    <el-table-column type="expand">
      <template #default="props">
        <el-input v-model="props.row.description" :autosize="{ minRows: 3, maxRows: 100 }" :readonly="true"
                  type="textarea"/>
      </template>
    </el-table-column>

    <!-- 列表 -->
    <el-table-column label="硬件厂商" min-width="150" prop="hardManufacturer"/>
    <el-table-column label="硬件型号" min-width="150" prop="hardDeviceType"/>
    <el-table-column label="软件厂商" min-width="150" prop="softManufacturer"/>
    <el-table-column label="软件型号" min-width="150" prop="softDeviceType"/>
    <el-table-column label="属组" min-width="150" prop="groupName"/>
    <el-table-column :formatter="formatDate4elTableColumn" label="更新日期" prop="updateTime" width="160"/>


    <!-- 上传对话框/下载对话框 -->
    <el-table-column align="center" label="操作" width="280">
      <template #default="scope">
        <el-upload
            v-model:file-list="dataState.fileList"
            :before-upload="handleBeforeUpload"
            :http-request="(file)=>{return handleUpload(file,scope.row)}"
            :show-file-list="false"
            accept=".sota"
        >
          <el-button :icon="Key" circle plain type="primary" @click.stop="handleKeyDialog(scope.row)"/>
          <el-button slot="trigger" :icon="Upload" circle plain type="primary"/>
          <el-button :disabled="scope.row.lastVersion === undefined" :icon="Download" circle plain type="primary"
                     @click.stop="handleDownload(scope.row)"/>
          <el-button :icon="Edit" circle plain type="primary" @click.stop="handleEditDialog(scope.row)"/>
          <el-button :icon="Delete" circle plain type="danger" @click.stop="handleDelete(scope.row)"/>
          <el-button :icon="ArrowRight" circle plain type="primary" @click.stop="handleDetailPage(scope.row)"/>
        </el-upload>
      </template>
    </el-table-column>

  </el-table>

  <!-- 分页工具条 -->
  <pagination v-if="dataState.total > 0" v-model:limit="dataState.queryParams.pageSize"
              v-model:page="dataState.queryParams.pageNum" :total="dataState.total"
              @pagination="handleQuery"/>
</template>

<script lang="ts" setup>
import {onMounted, reactive} from "vue";
import {Key, Download, Upload, ArrowRight, Delete, Edit} from '@element-plus/icons-vue';
import {useRouter} from "vue-router";
import {ElMessage, UploadRawFile, UploadRequestOptions, UploadUserFile} from "element-plus";

import {
  RepoCompEntity,
  RepoCompQueryParam,
} from "@/api/cloud/repository/repocomp/haas/types";
import {
  listRepoCompEntityPages, downloadFiles, uploadFile
} from "@/api/cloud/repository/repocomp/haas";
import {formatDate4elTableColumn,} from '@/utils/formatter';

const props = defineProps(['modelType'])
const emit = defineEmits(['rowClick', 'update', 'delete', 'updateKey', 'updateVersion']);// 定义组件的事件通知
const router = useRouter();

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({refreshTable});

// 数据状态：定义
let dataState = reactive({
  // 页面转载状态
  loading: false,
  // 选中ID数组
  ids: [],
  // 记录总数
  total: 0,
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 查询参数
  queryParams: {pageNum: 1, pageSize: 10} as RepoCompQueryParam,
  // 实体数据
  entityList: [] as RepoCompEntity[],
  // 文件列表
  fileList: [] as UploadUserFile[],
});

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
  if (file.size > 100 * 1048 * 1048) {
    ElMessage.warning('上传文件不能大于100M');
    return false;
  }

  return true;
}

async function handleUpload(options: UploadRequestOptions, row: any): Promise<any> {
  // 上传API调用
  uploadFile(options.file, row.hardManufacturer, row.hardDeviceType, row.softManufacturer, row.softDeviceType, '').then(() => {
    dataState.fileList = [];
    ElMessage.success('上传成功！');

    handleQuery();
  })
}

function handleDownload(row: any) {
  let fileName = row.originalFilename;
  let uri = 'http://repository.fox-tech.cn/haas/' + row.hardManufacturer + '/' + row.hardDeviceType + '/' + row.softManufacturer + '/' + row.softDeviceType + '/' + row.lastVersion.fileName;
  downloadFiles(fileName, uri);
}

/**
 * 捕获列表中的行选择
 * @taskParam row
 */
function handleRowClick(row: any) {
  emit('rowClick', row);
}


function handleEditDialog(row: any) {
  emit('update', 'table', 'update', row);
}

function handleKeyDialog(row: any) {
  emit('updateKey', row);
}

function handleDetailPage(row: any) {
  router.push('/repository/repocomp/haas/version?haasId=' + row.id);
}

/**
 * 刷新页面信息
 */
function handleQuery() {
  emit('rowClick', {});

  dataState.loading = true;

  dataState.entityList = [];
  listRepoCompEntityPages(dataState.queryParams).then(({data}) => {
    data.list.forEach(value => {
      dataState.entityList.push(value);
    });

    dataState.total = data.total;
    dataState.loading = false;
  });
}

function handleDelete(row: any) {
  emit('delete', row);
}

/**
 * 刷新表单
 */
function refreshTable(queryParams: RepoCompQueryParam) {
  dataState.queryParams = queryParams;
  if (dataState.queryParams.ownerId === '') {
    dataState.queryParams.ownerId = undefined;
  }
  if (dataState.queryParams.groupName === '') {
    dataState.queryParams.groupName = undefined;
  }
  if (dataState.queryParams.hardManufacturer === '') {
    dataState.queryParams.hardManufacturer = undefined;
  }
  if (dataState.queryParams.hardDeviceType === '') {
    dataState.queryParams.hardDeviceType = undefined;
  }
  if (dataState.queryParams.softManufacturer === '') {
    dataState.queryParams.softManufacturer = undefined;
  }
  if (dataState.queryParams.softDeviceType === '') {
    dataState.queryParams.softDeviceType = undefined;
  }
  if (dataState.queryParams.keyword === '') {
    dataState.queryParams.keyword = undefined;
  }

  handleQuery();
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  handleQuery();
});

</script>
